# -*- coding: utf-8 -*-
__author__ = 'Paul'
from plone.app.layout.viewlets.interfaces import IAboveContent
from plone.app.layout.viewlets.interfaces import IAboveContentBody
from Products.CMFCore.utils import getToolByName
from plone.dexterity.interfaces import IDexterityContent
from plone.app.layout.globals.interfaces import IViewView
from Products.bpTheme.interfaces import IBpTheme
from zope.interface import Interface
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.layout.globals.interfaces import IViewView
from Products.ATContentTypes.interface import IATFolder
from zope.site.hooks import getSite
from zope.component import getMultiAdapter
from Products.bpContents.libro import ILibro
from Products.bpContents.articulo import IArticulo
from Products.bpContents.galeria import IGaleria
from plone.memoize.instance import memoize
from  plone.app.layout.viewlets.interfaces import IPortalTop
from zope.interface import Interface
from Acquisition import aq_parent, aq_inner
from zope.container.interfaces import IOrderedContainer
from Products.bpContents.utils import Utilidades


from Acquisition import aq_inner

# Use template files with acquisition support
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

# Import default Plone viewlet classes
from plone.app.layout.viewlets import common as base


"""
def render_viewlet(factory, context, request):
     ###Helper method to render a viewlet
    context = aq_inner(context)
    viewlet = factory(context, request, None, None).__of__(context)
    viewlet.update()
    return viewlet.render()
"""

class FloatingMenuViewlet(base.ViewletBase):


    @memoize
    def getEnlaces(self):
        """devueve los elementos para el menu"""
        ploneTool = getToolByName(self.context, 'portal_url')
        sitioPlone=ploneTool.getPortalObject()



        textUtil=Utilidades()
        resultado=[]
        homeFolder = aq_inner(sitioPlone["home"])
        folder_path = '/'.join(homeFolder.getPhysicalPath())
        interese_path='/'.join(getattr(homeFolder,"intereses").getPhysicalPath())
        levelOFolders=self.buscaContenidos(folder_path )



        ##results = catalog()
        ##results = catalog.searchResults(portal_type=('Folder','Directorio'),path={'query': folder_path, 'depth': 1})

        resultado.append({"titulo":"Intereses","contenido": self.buscaContenidos(interese_path),"url":interese_path})


        for lCero in levelOFolders:
            elemO=self.context.unrestrictedTraverse(lCero["path"])
            resultado.append({"titulo":elemO.Title(),
                              "contenido":self.buscaContenidos(lCero["path"]),
                              "url":elemO.absolute_url()})


        return resultado

    def dametexto(self):
        return "mega"

    def n_root_url(self):
        """devulve la ruta al home"""
        str="/"
        if self.request["ACTUAL_URL"].find(":")!=-1:
            str=self.context.portal_url()
        rStr=str.replace("/publica","")

        return rStr


    def buscaContenidos(self,folder_path):
        """Busca los primeros elementos que sean una carpeta dada una ruta"""
        catalog=getToolByName(self.context, 'portal_catalog')
        results=[]
        queryO= catalog.searchResults(portal_type=('Folder','Products.bpContents.directorio'),path={'query': folder_path, 'depth': 1})
        for elem in queryO:
            miOB=self.context.unrestrictedTraverse(elem.getPath())
            if miOB.getExcludeFromNav() == False or folder_path=="/publica/home/intereses":
                results.append(self.empaqueta(miOB))
        return results




    def empaqueta(self,objeto):
        """recibe un objeto y devuelve un diccionario de datos"""
        return {"titulo": objeto.Title(), "url":objeto.absolute_url(),"path":"/".join(objeto.getPhysicalPath())}


    def getURL(self):
        """devuelve la absolute_url"""
        return self.context.absolute_url()

    def getPersonalBar(self):
        """Devuelve el viewlet de la personal bar"""
        # Customized viewlet
        from plone.app.layout.viewlets.common import PersonalBarViewlet
        return self.renderViewlet(PersonalBarViewlet)


    def update(self):
        pass__author__ = 'Paul'



    def renderViewlet(self, viewlet_class):
        """ Render one viewlet

        @param viewlet_class: Class which manages the viewlet
        @return: Resulting HTML as string
        """
        return render_viewlet(viewlet_class, self.context, self.request)


    def get_position_in_parent(self,obj):
        """ Use IOrderedContainer interface to extract the object's manual ordering position
        """
        parent = obj.aq_inner.aq_parent
        ordered = IOrderedContainer(parent, None)
        if ordered is not None:
            return ordered.getObjectPosition(obj.getId())
        return 0

    def sort_by_position(self,a, b):
        """
        Python list sorter cmp() using position in parent.

        Descending order.
        """
        return self.get_position_in_parent(a) - self.get_position_in_parent(b)
